package com.cljh.controller;

import com.cljh.bean.Chat.DataMessage;
import com.cljh.config.AuthAccess;
import com.cljh.controller.page.Code;
import com.cljh.controller.page.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping("/chat")
public class ChatController {
    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @AuthAccess
    @PostMapping
    public Result setDataMessage(@RequestBody DataMessage dataMessage) {
        synchronized (dataMessage){
            String key = dataMessage.getUsername() +"-"+ dataMessage.getToName();
            String s = stringRedisTemplate.opsForValue().get(key);
//        System.out.println(s);
//        String[] split = s.split("-");
            if (s == null) {
                stringRedisTemplate.opsForValue().set(key, dataMessage.getContent());
            } else {
                stringRedisTemplate.opsForValue().set(key, s + dataMessage.getContent());
            }
        }

        return new Result(Code.SAVE_OK, null, "发送成功");
    }

    @GetMapping("/{username}/{toName}")
    public Result getDataMessage(@PathVariable String toName, @PathVariable String username) {
        String key=username+"-"+toName;
//        System.out.println(key);
        String s = stringRedisTemplate.opsForValue().get(key);
//        System.out.println(s);


        Integer code=s !=null ? Code.GET_OK:Code.GET_ERR;
        String msg=s!=null ? "查询到信息":"未查询到信息";
        return new Result(code,s,msg);

    }



}
